// pages/movie/movie.js
var app = getApp();

var utils = require("../util/utils.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    inTheaters: [],
    comingSoon: [],
    top250: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var inTheaters = app.globalUrl.doubanUrl + `/v2/movie/in_theaters?start=0&count=3`;
    var comingSoon = app.globalUrl.doubanUrl + `/v2/movie/coming_soon?start=0&count=3`;
    var top250 = app.globalUrl.doubanUrl + `/v2/movie/top250?start=0&count=3`;
    this.http(inTheaters, this.callback1, 'inTheaters', '正在热映');
    this.http(comingSoon, this.callback1, 'comingSoon', '即将上映');
    this.http(top250, this.callback1, 'top250', '排行榜');
  },

  http: function(url, callback, category, categoryName) {
    wx.request({
      url: url,
      header: {
        // 'content-type': 'application/xml'
        'content-type': 'json'
      },
      success: (data) => {
        callback(data.data, category, categoryName)
      }
    })
  },
  callback1: function(res, category, categoryName) {
    //处理数据 数据的过滤和存储
    //电影图片
    // 标题
    // 星星
    // 评分
    // id
    var movies = [];
    for (var idx in res.subjects) {
      var subject = res.subjects[idx];
      var title = subject.title;
      //名字过长处理一下
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...';
      };
      var temp = {
        coverageUrl: subject.images.large,
        title: title,
        star: utils.covertToStarsArray(subject.rating.stars),
        average: subject.rating.average,
        movieid: subject.id
      }
      movies.push(temp)
    }
    // console.log(movies);
    var readyData = {};
    readyData[category] = {
      categoryName: categoryName,
      movies: movies
    }
    console.log(readyData)
    this.setData(readyData)
  },
  movieMoreTap: function(e) {
    var categoryName = e.currentTarget.dataset.categoryname;
    wx.navigateTo({
      url: 'movie-more/movie-more?categoryName=' + categoryName,
    })
  }

})